#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import os
import shutil
import click
from core import ProjectMapping
from command import command
from logger import logger
from conf import config
from core.install import UnifyBuildInstallVerify


def obs_binary_rpm_download(branch, package, arch):
    p_map = ProjectMapping()
    projects = p_map.branch_project(branch=branch)
    if not projects:
        click.echo(
            click.style(
                "There is no project corresponding to the target branch", fg="red"
            )
        )
        exit(1)
    logger.info(projects)
    for project in projects:
        code, out, _ = command(
            cmds=["osc", "getbinaries", project, package, "standard_" + arch, arch],
            cwd=os.path.join(config.workspace, "old_rpms"),
        )
        logger.info(f"project: {project} code: {code}")
        if not code:
            logger.info("Downloading the archive rpm package is complete")
            exit(0)
    logger.error("Failed to download the archive binary package.")


def ebs_binary_rpm_download(package, arch):
    cmds = f"ccb select builds build_id={config.build_id} -f ground_projects"
    code, out, error = command(cmds=cmds.split())
    if code:
        logger.error(
            f"Failed to get the ground projects,command: {cmds} error: {error}."
        )
        exit(1)
    try:
        logger.info(out)
        ground_projects = UnifyBuildInstallVerify.json_loads(out)
        logger.info(ground_projects)
        project = ground_projects[-1]["_source"]["ground_projects"][0]["name"]
    except (ValueError, IndexError, KeyError):
        logger.error(
            f"Failed to get the repo ID of the ground project, build id: {config.build_id}"
        )
        exit(1)

    cmds = f"ccb download os_project={project} packages={package} architecture={arch} -b all"
    code, out, _ = command(
        cmds=cmds.split(), cwd=os.path.join(config.workspace, "old_rpms")
    )
    logger.info(f"project: {project} code: {code}")
    folder = os.path.join(config.workspace, "old_rpms", f"{project}-{arch}-{package}")
    if code or not os.path.exists(folder):
        logger.error("Failed to download the archive binary package.")
        exit(1)
    for rpm_file in os.listdir(folder):
        if not os.path.isfile(os.path.join(folder, rpm_file)):
            continue
        shutil.move(
            os.path.join(folder, rpm_file),
            os.path.join(config.workspace, "old_rpms", rpm_file),
        )
    shutil.rmtree(folder)
    logger.info("Downloading the archive rpm package is complete")


@click.command("download", help="下载二进制rpm包")
@click.option("-p", "--package", help="软件包名称")
@click.option(
    "-a",
    "--arch",
    help="软件架构",
    type=click.Choice(["x86_64", "aarch64"], case_sensitive=False),
    default="x86_64",
    show_default=True,
    required=True,
)
@click.option("-b", "--branch", help="目标分支")
def download_rpm(package, arch, branch):
    click.echo("Start download binary rpm")
    if config.build_env == "obs":
        obs_binary_rpm_download(branch, package, arch)
    else:
        ebs_binary_rpm_download(package, arch)


__all__ = "checkabi"
